package com.fengye.security.captcha.filter.filter;

import com.fengye.security.captcha.filter.exception.VerificationCodeException;
import com.fengye.security.captcha.filter.security.MyAuthenticationFailureHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 专门用于校验验证码的过滤器<br />
 *
 * 继承自 {@link OncePerRequestFilter}
 * 确保一次请求只会通过一次该过滤器(Filter 实际上并不能保证这一点)
 * @author sky
 * @date 2021年06月01日 10:03 上午
 */
@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {
    private final AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 非登录请求不校验验证码
        if (!"/auth/form".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
        } else {
            try {
                verificationCode(request);
                filterChain.doFilter(request, response);
            } catch (VerificationCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
    }

    private void verificationCode(HttpServletRequest request) {
        String requestCode = request.getParameter("captcha");
        HttpSession session = request.getSession();
        String savedCode = (String) session.getAttribute("captcha");

        // 无论成功与否,session 中的验证码被获取一次后立马重置
        if (StringUtils.hasText(savedCode)) {
            session.removeAttribute("captcha");
        }

        if (StringUtils.hasText(requestCode) && StringUtils.hasText(savedCode) && requestCode.equals(savedCode)) {
            log.info("=============验证码校验成功=============");
        }else {
            throw new VerificationCodeException();
        }
    }
}
